import { logger } from './logger';
import common from '@ohos.app.ability.common';
import preferences from '@ohos.data.preferences';

export class db {
  private static _instance: db;

  static get instance(): db {
    return this._instance;
  }

  static createInstance(context: common.Context): db {
    if (this._instance == null)
      this._instance = new db(context);
    return this._instance;
  }

  private readonly preference: preferences.Preferences;

  private constructor(context: common.Context) {
    this.preference = preferences.getPreferencesSync(context, { name: 'db' });
  }

  query<T>(key: string): T {
    let value = this.preference.getSync(key, '');
    return value ? value as T : undefined;
  }

  update(key: string, value: preferences.ValueType) {
    try {
      this.preference.putSync(key, value);
    } catch (err) {
      logger.instance.error(err);
    }
  }

  async updateAwait(key: string, value: preferences.ValueType) {
    try {
      this.preference.putSync(key, value);
      await this.preference.flush();
    } catch (err) {
      logger.instance.error(err);
    }
  }

  async flush() {
    await this.preference.flush();
  }
}